package cn.wolfcode.rocketmq._00_sendway;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.util.concurrent.CountDownLatch;

public class Producer {
    public static void main(String[] args) throws Exception {
        // 实例化消息生产者Producer
        DefaultMQProducer producer = new DefaultMQProducer("producer-sendway");
        // 设置NameServer的地址
        producer.setNamesrvAddr("localhost:9876");
        // 启动Producer实例
        producer.start();
        final CountDownLatch count = new CountDownLatch(100);
        for (int i = 0; i < 100; i++) {
            // 创建消息，并指定Topic，Tag和消息体
            Message msg = new Message("02-sendway" /* Topic */,
                    "TagA" /* Tag */,
                    ("Hello RocketMQ " + i).getBytes("utf-8") /* Message body */
            );
            //发送同步消息到一个Broker
            producer.send(msg, new SendCallback() {
                //@Override
                public void onSuccess(SendResult sendResult) {
                    //异步发送回调成功需要生产者正常运作
                    count.countDown();
                    System.out.println("消息发送成功");
                    //System.out.println(JSON.toJSONString(sendResult));
                }

                //@Override
                public void onException(Throwable e) {
                    count.countDown();
                    //System.out.println("消息发送失败"+e.getMessage());
                    System.out.println("处理失败消息");
                }
            });
        }
        count.await();
        // 如果不再发送消息，关闭Producer实例。
        producer.shutdown();
    }
}
